package com.zmn.oms.business.impl.orderattachment;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.conf.attachment.ConfOrderAttachmentBService;
import com.zmn.oms.business.interfaces.masterphoto.OrderPhotoBService;
import com.zmn.oms.business.interfaces.orderattachment.OrderAttachmentBService;
import com.zmn.oms.business.interfaces.work.masterwork.MasterWorkBService;
import com.zmn.oms.business.interfaces.yeyxplus.YeyxPlusBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.orderattachment.ModifyOrderAttachmentDTO;
import com.zmn.oms.model.dto.work.masterwork.OrderImageDTO;
import com.zmn.oms.model.entity.conf.attachment.ConfOrderAttachment;
import com.zmn.oms.model.entity.conf.attachment.ConfOrderAttachmentCategory;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.orderattachment.OrderAttachment;
import com.zmn.oms.model.entity.orderattachment.OrderAttachmentQuery;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.attachmen.OrderWorkAttachmentDetailVO;
import com.zmn.oms.model.vo.work.attachmen.OrderWorkAttachmentVO;
import com.zmn.oms.services.interfaces.conf.attachment.ConfOrderAttachmentCategoryService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.orderattachment.OrderAttachmentService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述：工单附件
 * 因迁移拆分旧附件数据，需要一个符合新需求的工单附件逻辑处理类。
 *
 * @author liuying
 * @date 2021/06/14 18:25
 * @see com.zmn.oms.business.impl.attachment.AttachmentBServiceImpl
 */
@Slf4j
@Service
@Deprecated
public class OrderAttachmentBServiceImpl implements OrderAttachmentBService {

    @Resource
    private OrderAttachmentService orderAttachmentService;
    @Resource
    private OrderPhotoBService orderPhotoBService;
    @Resource
    private MasterWorkBService masterWorkBService;
    @Resource
    private OrderWorkService orderWorkService;
	@Resource
	private ConfOrderAttachmentCategoryService confOrderAttachmentCategoryService;
	@Resource
	private ConfOrderAttachmentBService confOrderAttachmentBService;
	@Resource
	private OrderExtendService orderExtendService;
    @Autowired
    private YeyxPlusBService yeyxPlusBService;

	@NacosValue(value="${app.h5.attachment.appEgUrl:https://test2-h5-mapp.xiujiadian.com/product?confAttachmentId=%s}", autoRefreshed = true)
	private String appEgUrl;

    @Override
    public OrderWorkAttachmentVO getOrderAttachmentByOrderWork(OrderWork orderWork) {
        OrderAttachmentQuery orderAttachmentQuery = new OrderAttachmentQuery();
        orderAttachmentQuery.setOrderId(orderWork.getOrderId());
        orderAttachmentQuery.setWorkId(orderWork.getWorkId());
        orderAttachmentQuery.setBizType(orderWork.getBizType());
        orderAttachmentQuery.setChannelId(orderWork.getChannelId());
        orderAttachmentQuery.setServCategId(orderWork.getServCategId());
        OrderWorkAttachmentVO orderWorkAttachmentVO = this.getOrderAttachmentByQuery(orderAttachmentQuery);

        // 页面显示需要过滤没有上传的附近
        if (CollectionUtils.isNotEmpty(orderWorkAttachmentVO.getPictureList())) {
            List<OrderWorkAttachmentDetailVO> collect = orderWorkAttachmentVO.getPictureList().stream().filter(item -> Objects.nonNull(item.getAttachmentId())).collect(Collectors.toList());
            orderWorkAttachmentVO.setPictureList(collect);
        }

        if (CollectionUtils.isNotEmpty(orderWorkAttachmentVO.getServiceVideoList())) {
            List<OrderWorkAttachmentDetailVO> collect = orderWorkAttachmentVO.getServiceVideoList().stream().filter(item -> Objects.nonNull(item.getAttachmentId())).collect(Collectors.toList());
            orderWorkAttachmentVO.setServiceVideoList(collect);
        }

        return orderWorkAttachmentVO;
    }

    /**
     * 工单附件
     *
     * @param orderAttachmentQuery
     * @return
     */
    @Override
    public OrderWorkAttachmentVO getOrderAttachmentByQuery(OrderAttachmentQuery orderAttachmentQuery) {
        Objects.requireNonNull(orderAttachmentQuery);
        Objects.requireNonNull(orderAttachmentQuery.getOrderId());

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderAttachmentQuery.getOrderId(), orderAttachmentQuery.getWorkId());
        log.info("照片配置查询出的工单:{}",orderWork);
        // 兼容没有传服务分类或业务线
        if (Objects.isNull(orderAttachmentQuery.getServCategId()) || Objects.isNull(orderAttachmentQuery.getBizLine())) {
            orderAttachmentQuery.setBizType(orderWork.getBizType());
            orderAttachmentQuery.setChannelId(orderWork.getChannelId());
            orderAttachmentQuery.setServCategId(orderWork.getServCategId());
            orderAttachmentQuery.setBizLine(orderWork.getBizLine());
            orderAttachmentQuery.setProductId(orderWork.getShowProductId());
            orderAttachmentQuery.setCityId(orderWork.getCityId());
        }

        // 查询已保存的附件资源
        List<OrderAttachment> orderAttachments = orderAttachmentService.listAttachmentByOrderId(orderAttachmentQuery.getOrderId());
        Map<Integer, OrderAttachment> attachmentMap = orderAttachments.stream()
                .collect(Collectors.toMap(OrderAttachment::getType, OrderAttachment -> OrderAttachment, (value1, value2) -> {
                    return value1;
                }));

        OrderWorkAttachmentVO orderWorkAttachmentVO = new OrderWorkAttachmentVO();
        // 图片附件
        orderWorkAttachmentVO.setPictureList(this.getOrderPictureAttachmentList(orderAttachmentQuery, attachmentMap));
        // 视频附件
        orderWorkAttachmentVO.setServiceVideoList(this.getOrderVideoAttachmentList(orderAttachmentQuery, attachmentMap));

        // app 调用时兼容处理
        this.filterEquipmentPicture(orderWorkAttachmentVO, orderAttachmentQuery.getAppPlat(), orderAttachmentQuery.getVersion());

        // 言而有信不处理贴画照
        boolean isYeyx = yeyxPlusBService.isYeyxPilot(orderWork.getCompanyId(), orderWork.getCityId(), orderWork.getMasterId());
        if (isYeyx) {
            orderWorkAttachmentVO.setPictureList(orderWorkAttachmentVO.getPictureList().stream().filter(e -> !Objects.equals(e.getType(), OrderAttachmentTypeEnum.THZ.getCode())).collect(Collectors.toList()));
        }

        return orderWorkAttachmentVO;
    }

    /**
     * 兼容处理 过滤装备照
     * Android 107及以下不返回
     * IOS 108及以下不返回 装备照
     *
     * @param orderWorkAttachmentVO
     * @param appPlat
     * @param version
     */
    private void filterEquipmentPicture(OrderWorkAttachmentVO orderWorkAttachmentVO, Integer appPlat, Integer version) {
        if (Objects.isNull(appPlat) || Objects.isNull(version)) {
            return;
        }

        if (Objects.equals(appPlat, AppConsts.APP_OS_IOS)) {
            if (version > 113) {
                // 老版本，不显示配件新旧照片
                orderWorkAttachmentVO.setPictureList(orderWorkAttachmentVO.getPictureList().stream()
                        .filter(e ->
                                !Objects.equals(e.getType(), OrderAttachmentTypeEnum.JPJZP.getCode()) && !Objects.equals(e.getType(), OrderAttachmentTypeEnum.XPJZP.getCode()))
                        .collect(Collectors.toList()));
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_ATTACHMENT_IMAGE, beforeProceed = false)
    public void modifyOrderWorkAttachment(ModifyOrderAttachmentDTO modifyOrderAttachmentDTO) throws OmsBaseException {
        Objects.requireNonNull(modifyOrderAttachmentDTO.getOrderId(), "订单ID不能为空");
        Objects.requireNonNull(modifyOrderAttachmentDTO.getType(), "附件类型不能为空");

        List<OrderAttachment> orderAttachmentList = orderAttachmentService.listAttachmentByOrderIdSrcMaster(modifyOrderAttachmentDTO.getOrderId());
        OrderAttachment orderAttachment = orderAttachmentList.stream().filter(e -> Objects.equals(e.getType(), modifyOrderAttachmentDTO.getType())).findFirst().orElse(null);

        // 审核状态
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(modifyOrderAttachmentDTO.getOrderId(), modifyOrderAttachmentDTO.getOrderId());

        if (Objects.isNull(orderAttachment)) {
            // 新增
            if (StringUtil.isNotBlank(modifyOrderAttachmentDTO.getSrc())) {
                orderAttachment = BeanMapper.map(modifyOrderAttachmentDTO, OrderAttachment.class);

                OrderAttachmentQuery orderAttachmentQuery = OrderAttachmentQuery.builder()
                        .orderId(orderWork.getOrderId())
                        .workId(orderWork.getOrderId())
                        .type(modifyOrderAttachmentDTO.getType())
                        .bizType(orderWork.getBizType())
                        .channelId(orderWork.getChannelId())
                        .servCategId(orderWork.getServCategId()).build();

	            // 查询某个类型的照片配置
                ConfOrderAttachment configAttachment = confOrderAttachmentBService.getAttachmentConfigByQuery(orderAttachmentQuery);
                if(configAttachment == null){
	                log.info("（old）新增照片 - 订单号：[{}] 未查询出[type:{}]的附件配置。", orderWork.getOrderId(), modifyOrderAttachmentDTO.getType());
                }

	            // 是否需要后台审核
	            Boolean needReview = Objects.nonNull(configAttachment) && Objects.equals(configAttachment.getNeedReview(), GlobalConsts.YES);
	            if (needReview) {
		            orderAttachment.setNeedReview(configAttachment.getNeedReview());
		            orderAttachment.setReviewStatus(OrderConsts.IMAGE_REVIEW_STATUS_WAITING);
	            } else {
		            orderAttachment.setNeedReview(GlobalConsts.NO);
		            orderAttachment.setReviewStatus(OrderConsts.IMAGE_REVIEW_STATUS_NO);
	            }

                orderAttachmentService.insertAttachment(orderAttachment);
	            log.info("（old）照片附件操作 - 新增：{}", orderAttachment);

                if (needReview && Objects.equals(orderAttachment.getType(), OrderAttachmentTypeEnum.CONSTS_THZ)) {
                    orderPhotoBService.sendImageDetectionMessage(orderWork.getOrderId(), orderWork.getWorkId(), orderAttachment.getAttachmentId(), orderAttachment.getType());
                } else if (needReview && configAttachment != null && Objects.equals(configAttachment.getAutoAudit(), GlobalConsts.YES)) {
                    orderPhotoBService.sendImageDetectionMessage(orderWork.getOrderId(), orderWork.getWorkId(), orderAttachment.getAttachmentId(), orderAttachment.getType());
                }
            }
        } else {
            // 更新图片url
            String urls = masterWorkBService.convertUrls(orderAttachment.getSrc(), modifyOrderAttachmentDTO.getSrc(), modifyOrderAttachmentDTO.getOpType(), modifyOrderAttachmentDTO.getIndex());
            if (urls.startsWith(",")) {
                urls = urls.substring(1);
            }
            orderAttachment.setSrc(urls);
            if (urls.length() == 0) {
                orderAttachmentService.deleteByKey(orderAttachment.getAttachmentId());
                orderAttachment.setReviewStatus(OrderConsts.IMAGE_REVIEW_STATUS_NO);
            } else {
                if (Objects.equals(orderAttachment.getNeedReview(), GlobalConsts.NO)) {
                    orderAttachment.setReviewStatus(OrderConsts.IMAGE_REVIEW_STATUS_NO);
                } else {
                    orderAttachment.setReviewStatus(OrderConsts.IMAGE_REVIEW_STATUS_WAITING);
                }
                log.info("照片附件操作-修改(old)：{}", orderAttachment);
                orderAttachmentService.updateByKey(orderAttachment);
                if (Objects.equals(orderAttachment.getNeedReview(), GlobalConsts.YES) && Objects.equals(orderAttachment.getType(), OrderAttachmentTypeEnum.CONSTS_THZ)) {
                    orderPhotoBService.sendImageDetectionMessage(orderWork.getOrderId(), orderWork.getWorkId(), orderAttachment.getAttachmentId(), orderAttachment.getType());
                }
            }
        }

        // 如果是贴花照，既保存到附件表中，也保存到扩展表中，等到IOS升级到新版本之后，【删除本段代码】 - 2022年4月16日22:18:40
        if (Objects.nonNull(orderAttachment) && Objects.equals(orderAttachment.getType(), OrderAttachmentTypeEnum.CONSTS_THZ)) {
            OrderExtend orderExtend = new OrderExtend();
            orderExtend.setExtId(orderAttachment.getOrderId());
            orderExtend.setAppliqueSrc(orderAttachment.getSrc());
            orderExtendService.updateOrderExtend(orderExtend);

            OrderWork updateOrderWork = new OrderWork();
            updateOrderWork.setOrderId(orderWork.getOrderId());
            updateOrderWork.setWorkId(orderWork.getWorkId());
            updateOrderWork.setAppliqueStatus(orderAttachment.getReviewStatus());
            orderWorkService.updateOrderWorkByKey(updateOrderWork);

            log.info("照片附件操作-更新贴花照(old)：{}", orderAttachment);
        }

    }

    @Override
    public void modifyOrderWorkAttachment(OrderImageDTO orderImageDTO, OrderWork orderWork) throws OmsBaseException {
        List<OrderAttachment> orderAttachmentList = orderAttachmentService.listAttachmentByOrderIdSrcMaster(orderImageDTO.getOrderId());
        OrderAttachment orderAttachment = orderAttachmentList.stream().filter(e -> Objects.equals(e.getType(), OrderAttachmentTypeEnum.CONSTS_THZ)).findFirst().orElse(null);

        if (Objects.isNull(orderAttachment)) {
            // 新增
            if (StringUtil.isNotBlank(orderImageDTO.getUrl())) {
                orderAttachment = BeanMapper.map(orderImageDTO, OrderAttachment.class);
                orderAttachment.setType(OrderAttachmentTypeEnum.CONSTS_THZ);
                orderAttachment.setSrc(orderImageDTO.getUrl());
                orderAttachment.setNeedReview(GlobalConsts.YES);
                orderAttachment.setReviewStatus(OrderConsts.IMAGE_REVIEW_STATUS_WAITING);
                orderAttachmentService.insertAttachment(orderAttachment);

                log.info("照片附件操作-新增(OrderImageDTO)：{}", orderAttachment);
            }
        } else {
            // 更新图片url
            orderAttachment.setSrc(orderImageDTO.getUrl());

            if (StringUtils.isBlank(orderImageDTO.getUrl())) {
                orderAttachmentService.deleteByKey(orderAttachment.getAttachmentId());
            } else {
                orderAttachmentService.updateByKey(orderAttachment);
                log.info("照片附件操作-修改(OrderImageDTO)：{}", orderAttachment);
            }
        }
    }

    /**
     * 工单照片附件
     *
     * @param orderAttachmentQuery
     * @param attachmentMap
     * @return
     */
    private List<OrderWorkAttachmentDetailVO> getOrderPictureAttachmentList(OrderAttachmentQuery orderAttachmentQuery, Map<Integer, OrderAttachment> attachmentMap) {

	    // 查询渠道图片配置
	    List<ConfOrderAttachment> pictureConfigList = confOrderAttachmentBService.listConfigOrderPictureAttachmentByQuery(orderAttachmentQuery);
	    if (CollectionUtils.isEmpty(pictureConfigList)) {
		    return Lists.newArrayList();
	    }

        Map<Integer, String> categoryNameMap;
	    List<Integer> categoryIds = pictureConfigList.stream().map(ConfOrderAttachment::getCategId).collect(Collectors.toList());
	    List<ConfOrderAttachmentCategory> categoryList = confOrderAttachmentCategoryService.listByIds(categoryIds);
	    log.info("（old）获取工单“照片” - 查询【附件分类】信息 入参：{} 出参：{}", categoryIds, categoryList);

	    if (CollectionUtils.isNotEmpty(categoryList)) {
		    categoryNameMap = categoryList.stream().collect(Collectors.toMap(ConfOrderAttachmentCategory::getCategId, ConfOrderAttachmentCategory::getCategName));
	    } else {
		    categoryNameMap = Maps.newHashMap();
	    }

	    // 组装VO对象
	    List<OrderWorkAttachmentDetailVO> detailVOList = Lists.newArrayListWithCapacity(pictureConfigList.size());
	    pictureConfigList.forEach(pictureConfig -> {
		    OrderWorkAttachmentDetailVO orderWorkAttachmentDetailVO = new OrderWorkAttachmentDetailVO();
		    // 老接口需要过滤掉的照片类型
		    if(OrderAttachmentTypeEnum.FILTER_PICTURE_LIST.contains(pictureConfig.getCategId())){
		    	return;
		    }
		    OrderAttachment orderAttachment = attachmentMap.get(pictureConfig.getCategId());
		    if (Objects.nonNull(orderAttachment)) {
			    BeanMapper.copy(orderAttachment, orderWorkAttachmentDetailVO);
		    }

		    if (StringUtils.isNotBlank(pictureConfig.getDetailDescription())) {
			    orderWorkAttachmentDetailVO.setEgUrl(String.format(appEgUrl, pictureConfig.getId()));
		    } else if (Objects.equals(pictureConfig.getCategId(), OrderAttachmentTypeEnum.CONSTS_ZBZ)) {
			    orderWorkAttachmentDetailVO.setEgUrl(OrderAttachmentConsts.UPLOAD_STANDARD_ZBZ_URL);
		    }
		    orderWorkAttachmentDetailVO.setType(pictureConfig.getCategId());
		    orderWorkAttachmentDetailVO.setTypeName(categoryNameMap.get(pictureConfig.getCategId()));
		    orderWorkAttachmentDetailVO.setRequiredFlag(pictureConfig.getMustUpload());
		    orderWorkAttachmentDetailVO.setNumber(pictureConfig.getNum());
		    orderWorkAttachmentDetailVO.setEgSrc(pictureConfig.getEgSrc());
		    orderWorkAttachmentDetailVO.setDescription(pictureConfig.getDescription());
		    orderWorkAttachmentDetailVO.setNeedReview(pictureConfig.getNeedReview());
		    orderWorkAttachmentDetailVO.setOrderDetailShow(pictureConfig.getOrderDetailShow());
		    detailVOList.add(orderWorkAttachmentDetailVO);
	    });

	    return detailVOList;
    }

    /**
     * 工单视频附件
     *
     * @param orderAttachmentQuery
     * @param attachmentMap
     * @return
     */
    private List<OrderWorkAttachmentDetailVO> getOrderVideoAttachmentList(OrderAttachmentQuery orderAttachmentQuery, Map<Integer, OrderAttachment> attachmentMap) {
        // 查询渠道视频配置
	    List<ConfOrderAttachment> videoConfigList = confOrderAttachmentBService.listConfigOrderVideoAttachmentByQuery(orderAttachmentQuery);
	    if (CollectionUtils.isEmpty(videoConfigList)) {
            return Lists.newArrayList();
        }

	    Map<Integer, String> categoryNameMap;
	    List<Integer> categoryIds = videoConfigList.stream().map(ConfOrderAttachment::getCategId).collect(Collectors.toList());
	    List<ConfOrderAttachmentCategory> categoryList = confOrderAttachmentCategoryService.listByIds(categoryIds);
	    log.info("（old）获取工单“视频” - 查询【附件分类】信息 入参：{} 出参：{}", categoryIds, categoryList);

	    if (CollectionUtils.isNotEmpty(categoryList)) {
		    categoryNameMap = categoryList.stream().collect(Collectors.toMap(ConfOrderAttachmentCategory::getCategId, ConfOrderAttachmentCategory::getCategName));
	    } else {
		    categoryNameMap = Maps.newHashMap();
	    }

        // 获取视频类型的附件
	    List<OrderWorkAttachmentDetailVO> attachmentDetailVOList = Lists.newArrayListWithCapacity(videoConfigList.size());
	    videoConfigList.forEach(videoConfig -> {
            OrderAttachment orderAttachment = attachmentMap.get(videoConfig.getCategId());

            OrderWorkAttachmentDetailVO orderWorkAttachmentDetailVO = new OrderWorkAttachmentDetailVO();
            if (Objects.nonNull(orderAttachment)) {
                BeanMapper.copy(orderAttachment, orderWorkAttachmentDetailVO);
                if (StringUtils.isNotBlank(orderAttachment.getSrc())) {
                    orderWorkAttachmentDetailVO.setVideoThumbnailSrc(String.format("%s?x-oss-process=video/snapshot,t_10000,m_fast", orderAttachment.getSrc()));
                }
            }
            orderWorkAttachmentDetailVO.setType(videoConfig.getCategId());
            orderWorkAttachmentDetailVO.setTypeName(categoryNameMap.get(videoConfig.getCategId()));
            orderWorkAttachmentDetailVO.setRequiredFlag(videoConfig.getMustUpload());
            orderWorkAttachmentDetailVO.setNumber(videoConfig.getNum());
            // 视频链接地址
            orderWorkAttachmentDetailVO.setEgSrc(videoConfig.getEgSrc());
		    orderWorkAttachmentDetailVO.setDescription(videoConfig.getDescription());
            if (StringUtils.isNotBlank(videoConfig.getEgSrc())) {
                orderWorkAttachmentDetailVO.setEgVideoThumbnailSrc(String.format("%s?x-oss-process=video/snapshot,t_10000,m_fast", videoConfig.getEgSrc()));
            }

            attachmentDetailVOList.add(orderWorkAttachmentDetailVO);
        });

        return attachmentDetailVOList;
    }
}
